//
//  DJDCallVideoVC.m
//  HCVideoModule
//
//  Created by 蒋千秋 on 2021/9/23.
//

#import "DJDCallVideoVC.h"
#import "DJDVideoBottomView.h"
#import "WMDragView.h"
#import <MBProgressHUD+BJHubHelper.h>
#import "DJDAudioTools.h"
#import <ReactiveObjC.h>
#import <Masonry/Masonry.h>
#import "VideoWindow.h"
#import <HCBaseModule/HCConstant.h>
@interface DJDCallVideoVC ()<TRTCCloudDelegate>
@property (nonatomic,strong)DJDVideoBottomView *bottomView;
@property (nonatomic,strong)WMDragView *cameraView;
@property (nonatomic,strong)WMDragView *venderView;
@property (nonatomic,strong,nullable)VideoWindow *window;
@property (nonatomic,assign)BOOL venderViewIsMax;
@property (nonatomic,assign)BOOL isMinShow;
@property (nonatomic,strong)UIButton *minShowBtn;
@property (nonatomic, strong) dispatch_source_t timer;
@property (nonatomic,copy) NSString *exitType;
@end
@implementation DJDCallVideoVC
- (UIButton *)minShowBtn {
    if (!_minShowBtn) {
        _minShowBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_minShowBtn setTitle:@"最小化" forState:UIControlStateNormal];
        _minShowBtn.titleLabel.font = [UIFont systemFontOfSize:10];
        [_minShowBtn setBackgroundColor:UIColor.orangeColor];
        [_minShowBtn addTarget:self action:@selector(minShowAction) forControlEvents:UIControlEventTouchUpInside];
        _minShowBtn.frame = CGRectMake(20, 40, 40, 40);
        _minShowBtn.layer.cornerRadius = 20;
        _minShowBtn.layer.masksToBounds = YES;
    }
    return _minShowBtn;
}
- (void)minShowAction{
    self.isMinShow = YES;
}
- (void)setIsMinShow:(BOOL)isMinShow {
    _isMinShow = isMinShow;
    self.window.isMinShow = isMinShow;
    if (isMinShow) {
        [UIView animateWithDuration:kAnimationDuration animations:^{
            self.view.frame = CGRectMake(0, 0, kMinVideoWidth, kMinVideoHeight);
            self.venderView.frame = self.view.bounds;
        }];
        self.view.userInteractionEnabled = NO;
        self.cameraView.hidden = YES;
        self.bottomView.hidden = YES;
        self.minShowBtn.hidden = YES;
        self.window.dragEnable = YES;
    }else {
        [UIView animateWithDuration:kAnimationDuration animations:^{
            self.view.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
        }];
        self.view.userInteractionEnabled = YES;
        self.window.dragEnable = NO;
        self.cameraView.hidden = NO;
        self.bottomView.hidden = NO;
        self.minShowBtn.hidden = NO;
    }
}
- (instancetype)init
{
    self = [super init];
    if (self) {
        self.modalPresentationStyle = UIModalPresentationCustom;
    }
    return self;
}
- (WMDragView *)cameraView{
    if (!_cameraView) {
        _cameraView = [[WMDragView alloc] initWithFrame:CGRectMake(0, 0, kMinVideoWidth, kMinVideoHeight)];
        _cameraView.dragEnable = YES;
        _cameraView.isKeepBounds = YES;
        HCWeakSelf
        _cameraView.clickDragViewBlock = ^(WMDragView *dragView) {
            if (weakSelf.venderViewIsMax) weakSelf.venderViewIsMax = NO;
        };
    }
    return _cameraView;
}
- (WMDragView *)venderView{
    if (!_venderView) {
        _venderView = [[WMDragView alloc] initWithFrame:self.view.bounds];
        _venderView.isKeepBounds = YES;
        _venderView.dragEnable = NO;
        HCWeakSelf
        _venderView.clickDragViewBlock = ^(WMDragView *dragView) {
            if (!weakSelf.venderViewIsMax) weakSelf.venderViewIsMax = YES;
        };
    }
    return _venderView;
}
- (void)setVenderViewIsMax:(BOOL)venderViewIsMax{
    _venderViewIsMax = venderViewIsMax;
    if (venderViewIsMax) {
        [self.view insertSubview:self.venderView atIndex:0];
        self.venderView.frame = self.view.bounds;
        self.cameraView.frame = CGRectMake(kScreenWidth - kMinVideoWidth, 80, kMinVideoWidth, kMinVideoHeight);
        self.venderView.dragEnable = NO;
        self.cameraView.dragEnable = YES;
        [self.view insertSubview:self.cameraView aboveSubview:self.venderView];
        [self.view insertSubview:self.minShowBtn aboveSubview:self.cameraView];
    }else{
        [self.view insertSubview:self.cameraView atIndex:0];
        [self.view insertSubview:self.venderView aboveSubview:self.cameraView];
        [self.view insertSubview:self.minShowBtn aboveSubview:self.venderView];
        self.venderView.frame = CGRectMake(kScreenWidth - kMinVideoWidth, 80, kMinVideoWidth, kMinVideoHeight);
        self.venderView.dragEnable = YES;
        self.cameraView.dragEnable = NO;
        self.cameraView.frame = self.view.bounds;
    }
}
- (DJDVideoBottomView *)bottomView{
    if (!_bottomView) {
        _bottomView = [[DJDVideoBottomView alloc] init];
        _bottomView.isCallVideo = self.isCallVideo;
        _bottomView.vc = self;
    }
    return _bottomView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColor.whiteColor;
    [self initUI];
}
- (void)initUI{
    self.cameraView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
    [self.view addSubview:self.cameraView];
    [self.view addSubview:self.bottomView];
    [self.view addSubview:self.minShowBtn];
    HCWeakSelf
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        if (@available(iOS 11.0, *)) {
            make.bottom.mas_equalTo(weakSelf.view.mas_safeAreaLayoutGuideBottom);
            make.left.mas_equalTo(weakSelf.view.mas_safeAreaLayoutGuideLeft);
            make.right.mas_equalTo(weakSelf.view.mas_safeAreaLayoutGuideRight);
        } else {
            make.left.right.bottom.mas_equalTo(0);
        }
        make.height.mas_equalTo(190);
    }];
    
    TRTCCloud.sharedInstance.delegate = self;
    [TRTCCloud.sharedInstance enterRoom:self.params appScene:TRTCAppSceneVideoCall];
    [TRTCCloud.sharedInstance startLocalPreview:YES view:self.cameraView];
    if (self.isCallVideo) {
//        [DJDAudioTools.share playCallAudioForever:YES];
    }
    [[NSNotificationCenter.defaultCenter rac_addObserverForName:UIApplicationWillTerminateNotification object:nil] subscribeNext:^(NSNotification * _Nullable x) {
        //杀掉进程之前
        [TRTCCloud.sharedInstance exitRoom];
        if (weakSelf.exitRoomBlock) weakSelf.exitRoomBlock();
    }];
    
    //30s未接听自动挂断
    __block int times = 0;
//    [[[RACSignal interval:1 onScheduler:RACScheduler.mainThreadScheduler] takeUntil:[self rac_signalForSelector:@selector(onUserVideoAvailable:available:)]] subscribeNext:^(NSDate * _Nullable x) {
//        times ++;
//        if (times > 30){
//            [TRTCCloud.sharedInstance exitRoom];
//            [MBProgressHUD bjShowMessageHubWithMessage:@"对方未接听！"];
//            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                // 2秒后异步执行这里的代码...
//                weakSelf.window = nil;
//            });
//        }
//    }];
    
    
    //定时器
    //创建队列
    dispatch_queue_t queue = dispatch_get_main_queue();
    //创建定时器
    self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    //设置定时器时间
    dispatch_time_t start = dispatch_time(DISPATCH_TIME_NOW, 0);
    uint64_t interval = (uint64_t)(1.0 * NSEC_PER_SEC);
    dispatch_source_set_timer(self.timer, start, interval, 0);
    //启动定时器
    dispatch_resume(self.timer);
    //设置回调
    dispatch_source_set_event_handler(self.timer, ^{
        //重复执行的事件
        times++;
        NSLog(@"开始计时：%d",times);
        if (times > 30){
            
                    weakSelf.exitType = @"O";
                    [TRTCCloud.sharedInstance exitRoom];
                    [MBProgressHUD bjShowMessageHubWithMessage:@"对方未接听！"];
                        // 2秒后异步执行这里的代码...
                        weakSelf.window = nil;
                        //停止定时器
                       dispatch_source_cancel(weakSelf.timer);
                      weakSelf.timer = nil;
                }
    });
}
//已有对方进入房间
- (void)onUserVideoAvailable:(NSString *)userId available:(BOOL)available{
    [MBProgressHUD bjHideHubInView:self.view];
    if (self.isCallVideo) {
        [DJDAudioTools.share stopCallAudio];
    }
    if (available) {
        [TRTCCloud.sharedInstance startLocalAudio];
        [TRTCCloud.sharedInstance startRemoteView:userId view:self.venderView];
        self.venderViewIsMax = YES;
    } else {
        [TRTCCloud.sharedInstance stopRemoteView:userId];
        [TRTCCloud.sharedInstance exitRoom];
        self.window = nil;
    }
    [self.bottomView onUserVideoAvailable:userId available:available];
}
//进入房间失败
- (void)onError:(TXLiteAVError)errCode errMsg:(nullable NSString *)errMsg extInfo:(nullable NSDictionary*)extInfo{
    if (self.errorBlock) self.errorBlock(errCode, errMsg);
    if (self.isCallVideo) {
        [DJDAudioTools.share stopCallAudio];
    }
    [self.bottomView onError:errCode errMsg:errMsg extInfo:extInfo];
    [MBProgressHUD bjShowMessageHubWithMessage:[NSString stringWithFormat:@"%d",errCode]];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 2秒后异步执行这里的代码...
        self.window = nil;
    });
}
//进入房间
- (void)onEnterRoom:(NSInteger)result{
    if (self.enterRoomBlock) self.enterRoomBlock();
    NSString *msg = self.isCallVideo ? @"等待接听中" : @"正在连接中";
    [MBProgressHUD bjShowLoadingHubWithMessage:msg toView:self.view];
}
//对方离开房间
- (void)onRemoteUserLeaveRoom:(NSString *)userId reason:(NSInteger)reason{
    [TRTCCloud.sharedInstance exitRoom];
    [self.bottomView onRemoteUserLeaveRoom:userId reason:reason];
    [MBProgressHUD bjShowMessageHubWithMessage:@"对方已挂断！"];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 2秒后异步执行这里的代码...
        self.window = nil;
    });
}
//退出房间
- (void)onExitRoom:(NSInteger)reason{
    if (self.isCallVideo) {
        [DJDAudioTools.share stopCallAudio];
    }
    if (self.exitRoomBlock) self.exitRoomBlock();
    self.window = nil;
}
- (void)dealloc
{
    [TRTCCloud.sharedInstance exitRoom];
}
- (void)show{
    self.window = [[VideoWindow alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    self.window.rootViewController = self;
    self.isMinShow = NO;
    HCWeakSelf
    self.window.clickDragViewBlock = ^(WMDragView * _Nonnull dragView) {
        weakSelf.isMinShow = NO;
        weakSelf.venderViewIsMax = YES;
    };
}
@end
